Java IO 读取方式总结
Java IO 读取方式总结
Tinsiag Zhu1. Java NIO 最推荐使用
Java NIO (java.nio.file.Files)
读取文件最简单,代码最少的方法是使用Files类
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("src/1.txt"));
String line;
try {
while ((line = br.readLine())!= null){
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(br != null) br.close();
}
}
}
2. 经典写法:字符流 (BufferedReader)
这是处理纯文本的经典方式。使用 BufferedReader 可以通过缓冲提高读取效率,且支持按行读取。
场景: 逐行处理大文本文件,防止一次性加载到内存导致溢出。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
// 使用 try-with-resources 语法,自动关闭流,防止内存泄漏
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
String line;
// 循环读取每一行,直到读到 null
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 经典写法:字节流 (FileInputStream)
当你要读取非文本文件(图片、视频、压缩包)时,必须使用字节流。不能使用字符流,否则文件会损坏。
场景: 复制文件、网络传输文件。
import java.io.FileInputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("image.png")) {
// 创建一个缓冲区(例如 1KB)
byte[] buffer = new byte[1024];
int length;
// 循环读取,read 返回实际读取的字节数,-1 表示读完
while ((length = fis.read(buffer)) != -1) {
// 这里通常是写入到 OutputStream,或者处理字节数据
System.out.println("读取了 " + length + " 个字节");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. 特殊场景:读取 Classpath 资源 (Spring Boot常用)
在 Spring Boot 或 Maven 项目中,我们经常需要读取 src/main/resources 下的配置文件。此时不能用绝对路径(因为打包后是 jar 包),必须用 ClassLoader。
场景: 读取 src/main/resources/config.properties。
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class ResourceReadExample {
public static void main(String[] args) {
// 获取当前类的加载器读取资源
try (InputStream is = ResourceReadExample.class.getClassLoader().getResourceAsStream("config.txt")) {
if (is == null) {
System.out.println("文件未找到!");
return;
}
// 使用 Scanner 快速将 InputStream 转为文本
try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

